package com.tianbing.adlottery.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.tianbing.adlottery.helper.SkinUtils;
import com.tianbing.adlottery.util.ControllerFormBean;
import com.tianbing.adlottery.util.UserSession;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	static Logger logger = Logger.getLogger(LoginInterceptor.class);

	private SkinUtils skinUtils;

	private String viewPage;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		UserSession auth = (UserSession) skinUtils.getUserAuthorization(request, response);
		if (auth == null || auth != null && auth.isLogout() == true) {

			String url = request.getServletPath() + request.getPathInfo();

			String query = request.getQueryString();
			ModelAndView modelAndView = new ModelAndView(viewPage);
			ControllerFormBean fb = new ControllerFormBean();
			request.setAttribute("command", fb);
			logger.info("request.getServletPath()=" + request.getServletPath()+" request.getPathInfo()="+request.getPathInfo()+" query="+query);
			if (query != null) {
				modelAndView.getModel().put("loginForwardAction", url + "?" + query);
			} else {
				modelAndView.getModel().put("loginForwardAction", url);
			}
			throw new ModelAndViewDefiningException(modelAndView);
		} else {
			return true;
		}
	}

	public void setViewPage(String viewPage) {
		this.viewPage = viewPage;
	}

	public void setSkinUtils(SkinUtils skinUtils) {
		this.skinUtils = skinUtils;
	}

}
